package homework.six;

import java.sql.*;

public class DbUntil {

    // 数据库连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/usersDb";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "123456";

    /**
     * 获取数据库连接
     *
     * @return Connection 数据库连接对象
     * @throws ClassNotFoundException 如果找不到 JDBC 驱动类
     * @throws SQLException           如果数据库连接失败
     */
    public Connection getCon() throws ClassNotFoundException, SQLException {
        // 注册 MySQL JDBC 驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 建立数据库连接
        Connection conn = DriverManager.getConnection(URL, DB_USERNAME, DB_PASSWORD);

        return conn;
    }

    /**
     * 关闭数据库连接
     *
     * @param conn 要关闭的数据库连接
     */
    public void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println("关闭连接时发生错误：" + e.getMessage());
            }
        }
    }

    /**
     * 测试数据库连接是否成功
     */
    public static void main(String[] args) {
        DbUntil dbUtil = new DbUntil();
        try {
            Connection conn = dbUtil.getCon();
            if (conn != null) {
                System.out.println("数据库连接成功！");
                dbUtil.closeConnection(conn); // 关闭连接
            } else {
                System.out.println("数据库连接失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        try { if (rs != null) rs.close(); } catch (SQLException e) {}
        try { if (ps != null) ps.close(); } catch (SQLException e) {}
        try { if (conn != null) conn.close(); } catch (SQLException e) {}
    }
}
